package com.m4f.web.controller;

import java.io.IOException;
import java.util.List;
import java.util.logging.Logger;

import javax.cache.CacheException;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.m4f.utils.StackTraceUtil;
import com.m4f.business.model.BestPracticeType;
import com.m4f.business.model.request.ContactMail;
import com.m4f.business.service.AppConfigurationService;
import com.m4f.mail.Mailer;

@Controller
@RequestMapping("/contact")
public class ContactController extends BaseController {
	

	private static final Logger LOGGER = Logger.getLogger(ContactController.class.getName());
		
	@Autowired
	private Mailer mailer;
	@Autowired
	private AppConfigurationService appConfigurationService;

	public ContactController() throws CacheException {
		super();
	}
	
	@RequestMapping(method=RequestMethod.GET)
	public String getView(Model model) 
			throws IOException, ClassNotFoundException {
		return "contact/form";
	}
	
	@RequestMapping(method=RequestMethod.POST)
	public String receiveMail(@Valid ContactMail contactMail, 
			BindingResult result, Model model) {
		if (result.hasErrors()) {
			return "contact/form";
		}
		String message = "";
		String body = "Reported by: " + contactMail.getSender() + "\n";
		body += contactMail.getBody();
		try {
			mailer.sendEmail(this.appConfigurationService.getGlobalConfiguration().getAdminMail(), 
					this.appConfigurationService.getGlobalConfiguration().getAdminMail(), 
					contactMail.getSubject(), body);
		} catch(Exception e) {
			LOGGER.severe("Error sending mail: " + StackTraceUtil.getStackTrace(e));	
			message = this.getMessage("contact.action.mail.send.problem", null);
		}
		message = this.getMessage("contact.contact.mail.ok", null);
		model.addAttribute("message", message);
		return "common/thanks";
	}
	
	@ModelAttribute("contactMail")
	public ContactMail getBestPracticeTypes() {
		return new ContactMail();
	}
	
}